﻿#if !XBOX
using System;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate;
using Oops.Xna.Framework.Physics;

namespace Oops.Xna.Framework.Content.Pipeline.Serialization.Intermediate
{
	[ContentTypeSerializer()]
	public class ConstraintCollectionSerializer : ContentTypeSerializer<PhysicsComponent.ConstraintCollection>
	{
		private static ContentSerializerAttribute format = new ContentSerializerAttribute() { ElementName = "Item" };

		public override bool ObjectIsEmpty(PhysicsComponent.ConstraintCollection value)
		{
			return value.Count == 0;
		}

		public override bool CanDeserializeIntoExistingObject
		{
			get { return true; }
		}

		protected override PhysicsComponent.ConstraintCollection Deserialize(
			IntermediateReader input, 
			ContentSerializerAttribute format,
			PhysicsComponent.ConstraintCollection existingInstance)
		{
			if (existingInstance == null)
			{
				throw new InvalidOperationException("Oops!");
			}

			while (input.MoveToElement(ConstraintCollectionSerializer.format.ElementName))
			{
				input.ReadSharedResource<Constraint>(ConstraintCollectionSerializer.format, x => existingInstance.Add(x));
			}

			return existingInstance;
		}

		protected override void Serialize(
			IntermediateWriter output,
			PhysicsComponent.ConstraintCollection value, 
			ContentSerializerAttribute format)
		{
			foreach (var item in value)
			{
				output.WriteSharedResource(item, ConstraintCollectionSerializer.format);
			}
		}
	}
}
#endif
